from typing import List, Optional
from datetime import datetime
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.history import History, HistoryType
from app.schemas.history import HistoryCreate, HistoryUpdate

class CRUDHistory(CRUDBase[History, HistoryCreate, HistoryUpdate]):
    def create_prompt_history(
        self,
        db: Session,
        *,
        input_text: str,
        output_text: str,
        parameters: dict
    ) -> History:
        """创建提示词生成历史"""
        db_obj = History(
            type=HistoryType.PROMPT,
            input_text=input_text,
            output_text=output_text,
            parameters=parameters
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    
    def create_chat_history(
        self,
        db: Session,
        *,
        input_text: str,
        output_text: str,
        parameters: dict
    ) -> History:
        """创建对话历史"""
        db_obj = History(
            type=HistoryType.CHAT,
            input_text=input_text,
            output_text=output_text,
            parameters=parameters
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    
    def get_history_by_type(
        self,
        db: Session,
        history_type: HistoryType,
        skip: int = 0,
        limit: int = 100
    ) -> List[History]:
        """获取指定类型的历史记录"""
        return (
            db.query(History)
            .filter(History.type == history_type)
            .order_by(History.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )
    
    def get_recent_history(
        self,
        db: Session,
        limit: int = 10
    ) -> List[History]:
        """获取最近的历史记录"""
        return (
            db.query(History)
            .order_by(History.created_at.desc())
            .limit(limit)
            .all()
        )
    
    def get_multi(
        self,
        db: Session,
        *,
        skip: int = 0,
        limit: int = 100
    ) -> List[History]:
        """获取多条历史记录"""
        return (
            db.query(self.model)
            .order_by(self.model.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

history = CRUDHistory(History) 